<template>
    <div class="block" >
        <div class="info_block" style="background:white;">
            <el-row type="flex" class="row-bg" justify="left" style=" padding-top:12px;">
                <el-col :span="6">
                    <el-button type="primary" @click="sendMessage('sendMessageFrom')">发送</el-button>
                    <el-button  @click="resetMessageForm('sendMessageFrom')">重置</el-button>
                </el-col>
            </el-row>
        </div>
        <div class="from_block" style="background:white">
            <el-form ref="sendMessageFrom" :model="sendMessageFrom"  label-width="80px">
                <el-row style="padding-left:30px; padding-top:30px;">
                    <el-col :span="8">
                        <el-form-item label="消息标题:">
                            <el-input v-model="sendMessageFrom.subtitle" size="small "></el-input>
                        </el-form-item>
                    </el-col>
                </el-row> 
                <el-row style="padding-left:30px; margin-top:10px;">
                    <el-col :span="8">
                        <el-form-item label="用户范围:">
                            <el-radio-group v-model="sendMessageFrom.resource">
                            <el-radio label="1" >全部用户</el-radio>
                            <el-radio label="2" @change="checkUserShow"> 指定用户</el-radio>
                            </el-radio-group>
                            <el-link type="primary" v-show="shopShow" :underline="false" style="padding-left:30px;" @click="checkUser"><i class="el-icon-plus" ></i>添加用户</el-link>
                        </el-form-item>
                    </el-col>
                </el-row>   
                <el-row style="padding-left:30px; margin-top:10px;" >
                    <el-col :span="24">
                        <div >
                            <el-tag
                                v-for="tag in tags"
                                :key="tag"
                                closable
                                :disable-transitions="false"
                                @close="handleClose(tag)"
                                style="float:left;margin-left: 20px;">
                                {{tag}}
                            </el-tag>
                        </div>
                    </el-col>
                </el-row>  
                <el-row style="padding-left:30px; margin-top:10px;">
                    <el-col :span="24">
                        <el-form-item label="发送内容:">
                            <!-- 富文本编辑器 -->
                            <div class="editor_block">
                                <quill-editor
                                v-model="content"
                                ref="myQuillEditor"
                                :options="editorOption"
                                @focus="onEditorFocus($event)"
                                @blur="onEditorBlur($event)"
                                @change="onEditorChange($event)"
                                class="editor"
                                ></quill-editor>            
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>                                           
            </el-form>            
        </div>
        <!-- 指定用户弹窗 -->
        <div>
            <el-dialog title="选择用户"  :visible.sync="checkUserVisible"  :close-on-click-modal="false" center  >
                <div style="margin-bottom:50px;">
                    <el-form ref="formQueryUser" label-position="right" label-width="80px" :model="formQueryUser" >
                        <el-form-item 
                        prop="username"
                        label="用户名称:" 
                        size="mini" 
                        style="float:left;display: inline-block;"
                        >
                            <el-input v-model="formQueryUser.username"></el-input>
                        </el-form-item>
                        <el-form-item style="float:right;display: inline-block;" >
                            <el-button  icon="el-icon-search" size="small" type="success" @click="selectUser()"  >查询</el-button> 
                            <el-button icon="el-icon-refresh" @click="resetForm('formQueryUser')" size="small">重置</el-button>
                        </el-form-item>
                    </el-form>                    
                </div>
                <el-divider></el-divider>
                    <!--渲染数据  -->
                <div style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)" >
                    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="用户名" width="150">
                        <template slot-scope="scope">
                        <div>{{ scope.row.username }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="用户姓名" width="160">
                        <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top">
                            <p>用户姓名: {{ scope.row.personName }}</p>
                            <div slot="reference" class="name-wrapper">
                            <el-tag size="medium">{{ scope.row.personName }}</el-tag>
                            </div>
                        </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="联系电话" width="160">
                        <template slot-scope="scope">
                        <p>{{ scope.row.telephone }}</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="联系邮箱" width="160">
                        <template slot-scope="scope">
                        <div>{{ scope.row.email }}</div>
                        </template>
                    </el-table-column>
                </el-table>
                </div>
                <div style="margin-top:10px;margin-bottom:50px; ">
                    <!--prev表示上一页，next为下一页，pager表示页码列表,total表示总条目数，size用于设置每页显示的页码数量。-->
                    <el-pagination
                        background
                        layout="total,prev,sizes, pager, next,jumper"
                        :total="total"
                        :page-sizes="[2, 10, 15, 20]"
                        :page-size.sync="formSearch.pageSize"
                        :current-page.sync="formSearch.pageNum"
                        @current-change="getPage"
                        @size-change="getPage"
                        style="float: right">
                    </el-pagination>
                </div>   
                <el-divider></el-divider>                           
                <div slot="footer"  class="dialog-footer"  >
                    <el-button size="small" @click="checkUserVisible = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="checkUserVisible = false" >确 定</el-button>
                </div>
            </el-dialog>
        </div>        
    </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import "../../../styles/editor.css"

import { quillEditor } from "vue-quill-editor";
import {quillRedefine} from 'vue-quill-editor-upload'

import log from '../../../api/log';
import notice from '../../../api/notice';
import user from '../../../api/user';

import * as Quill from 'quill'  //引入编辑器
//quill图片可拖拽上传,允许粘贴图像并将其拖放到编辑器中。
import { ImageDrop } from 'quill-image-drop-module';
Quill.register('modules/imageDrop', ImageDrop);
//允许调整图像大小。
import ImageResize from "quill-image-resize-module"; // 引用
Quill.register("modules/imageResize", ImageResize); // 注册


const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{ indent: "-1" }, { indent: "+1" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{ direction: "rtl" }], // 文本方向-----[{'direction': 'rtl'}]
  [{ size: ["small", false, "large", "huge"] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ 'font': ['SimSun', 'SimHei', 'Microsoft-YaHei','XingKai', 'FangSong', 'Arial'] }], // 字体种类-----[{ font: [] }]
  [{ align: [] }], // 对齐方式-----[{ align: [] }]
  ["clean"], // 清除文本格式-----['clean']
  ["image", "video"] // 链接、图片、视频-----['link', 'image', 'video']
];
const titleConfig=[
    {Choice:'.ql-bold',title:'加粗'},
    {Choice:'.ql-italic',title:'斜体'},
    {Choice:'.ql-underline',title:'下划线'},
    {Choice:'.ql-header',title:'段落格式'},
    {Choice:'.ql-strike',title:'删除线'},
    {Choice:'.ql-blockquote',title:'块引用'},
    {Choice:'.ql-code',title:'插入代码'},
    {Choice:'.ql-code-block',title:'插入代码段'},
    {Choice:'.ql-font',title:'字体'},
    {Choice:'.ql-size',title:'字体大小'},
    {Choice:'.ql-list[value="ordered"]',title:'编号列表'},
    {Choice:'.ql-list[value="bullet"]',title:'项目列表'},
    {Choice:'.ql-direction',title:'文本方向'},
    {Choice:'.ql-header[value="1"]',title:'h1'},
    {Choice:'.ql-header[value="2"]',title:'h2'},
    {Choice:'.ql-align',title:'对齐方式'},
    {Choice:'.ql-color',title:'字体颜色'},
    {Choice:'.ql-background',title:'背景颜色'},
    {Choice:'.ql-image',title:'图像'},
    {Choice:'.ql-video',title:'视频'},
    {Choice:'.ql-link',title:'添加链接'},
    {Choice:'.ql-formula',title:'插入公式'},
    {Choice:'.ql-clean',title:'清除字体格式'},
    {Choice:'.ql-script[value="sub"]',title:'下标'},
    {Choice:'.ql-script[value="super"]',title:'上标'},
    {Choice:'.ql-indent[value="-1"]',title:'向左缩进'},
    {Choice:'.ql-indent[value="+1"]',title:'向右缩进'},
    {Choice:'.ql-header .ql-picker-label',title:'标题大小'},
    {Choice:'.ql-header .ql-picker-item[data-value="1"]',title:'标题一'},
    {Choice:'.ql-header .ql-picker-item[data-value="2"]',title:'标题二'},
    {Choice:'.ql-header .ql-picker-item[data-value="3"]',title:'标题三'},
    {Choice:'.ql-header .ql-picker-item[data-value="4"]',title:'标题四'},
    {Choice:'.ql-header .ql-picker-item[data-value="5"]',title:'标题五'},
    {Choice:'.ql-header .ql-picker-item[data-value="6"]',title:'标题六'},
    {Choice:'.ql-header .ql-picker-item:last-child',title:'标准'},
    {Choice:'.ql-size .ql-picker-item[data-value="small"]',title:'小号'},
    {Choice:'.ql-size .ql-picker-item[data-value="large"]',title:'大号'},
    {Choice:'.ql-size .ql-picker-item[data-value="huge"]',title:'超大号'},
    {Choice:'.ql-size .ql-picker-item:nth-child(2)',title:'标准'},
    {Choice:'.ql-align .ql-picker-item:first-child',title:'居左对齐'},
    {Choice:'.ql-align .ql-picker-item[data-value="center"]',title:'居中对齐'},
    {Choice:'.ql-align .ql-picker-item[data-value="right"]',title:'居右对齐'},
    {Choice:'.ql-align .ql-picker-item[data-value="justify"]',title:'两端对齐'}
];

export default {
    components: {
        quillEditor,
        quillRedefine
    },
    name:"editor",
    data(){
        return{
            // 富文本编辑器默认内容
            content: '',
            //富文本编辑器配置
            editorOption: {
                modules:{}
            },
            //发送消息文本
            sendMessageFrom: {
                resource: '',
                userIds:'',
                noticeInfo:'',
                subtitle:''

            },
            //指定用户弹窗
            checkUserVisible:false,
            checkUserFrom:{
                username:''
            },
            //隐藏添加用户
            shopShow: false,
            //添加用户
            tableData:[],
            total:0,
            formSearch:{
                pageNum:1,
                pageSize:10
            },
            //根据用户名称查询
            formQueryUser:{
                pageNum:1,
                pageSize:10,
                username:''
            },
            //多选框userId
            userIdsArray:[],
            //选中的用户
            tags:[],
        }
    },
    created(){
        this.editorOption = quillRedefine(
            {
                uploadConfig: {
                    action: '/api/file-center/file/uploadPicture',  // 必填参数 图片上传地址
                    // 必选参数  res是一个函数，函数接收的response为上传成功时服务器返回的数据
                    // 你必须把返回的数据中所包含的图片地址 return 回去
                    res: (respnse) => {
                        return respnse.data.fileUrl 
                    },
                    methods: 'POST',  // 可选参数 图片上传方式  默认为post
                    token: sessionStorage.token,  // 可选参数 如果需要token验证，假设你的token有存放在sessionStorage
                    name: 'file',  // 可选参数 文件的参数名 默认为img
                    size: 500,  // 可选参数   图片限制大小，单位为Kb, 1M = 1024Kb
                    accept: 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon',  // 可选参数 可上传的图片格式
                    start: () => {
                    },  // 可选参数 接收一个函数 开始上传数据时会触发
                    end: () => {
                    },  // 可选参数 接收一个函数 上传数据完成（成功或者失败）时会触发
                    success: () => {
                        this.$message.success("上传成功")
                    },  // 可选参数 接收一个函数 上传数据成功时会触发
                    error: () => {
                        this.$message.error("上传失败")
                    }  // 可选参数 接收一个函数 上传数据中断时会触发
                },
                // 以下所有设置都和vue-quill-editor本身所对应
                placeholder: '请输入正文',  // 可选参数 富文本框内的提示语
                theme: 'snow',  // 可选参数 富文本编辑器的风格
                // 可选参数 重定义的事件，比如link等事件
                toolOptions: toolbarOptions,
                handlers: {
                    
                },
            },
        )
        console.log(this.editorOption)
    },
    mounted(){
        this.initTitle()
    },
    methods:{
        //工具栏提示功能
        initTitle () {
            document.getElementsByClassName('ql-editor')[0].dataset.placeholder = ''
            for (let item of titleConfig) {
                let tip = document.querySelector('.quill-editor ' + item.Choice)
                if (!tip) continue
                tip.setAttribute('title', item.title)
            }
        },   
        resetMessageForm(sendMessageFrom) {
            // resetFields只对有检验规则的字段才会生效
            this.$refs[sendMessageFrom].resetFields();
            this.sendMessageFrom.userIds = ''
            this.sendMessageFrom.subtitle = ''
            this.sendMessageFrom.noticeInfo = ''
            this.sendMessageFrom.resource = ''

            
            this.content = ''

        },
        //失去焦点事件
        onEditorBlur(quill) {
        },
        //获得焦点事件
        onEditorFocus(quill) {

        },
        // 准备富文本编辑器
        onEditorReady(quill) {
        },
        //内容改变事件
        onEditorChange({ quill, html, text }) {
            this.content = html
            this.sendMessageFrom.noticeInfo=html;
        },
        //发送消息
        async sendMessage(){
            const res = await notice.sendMessage(this.sendMessageFrom);
            if(res.data.code === '000'){
            try {
                this.$refs['sendMessageFrom'].resetFields()
            } catch (err) {

            }
                this.$message.success("发送成功")
            }

        },
        //
        checkUserShow(){
            this.shopShow = true
        },
        //选择指定用户
        checkUser(){
            this.checkUserVisible = true
            this.getPage();
        },
            //用户分页
        async getPage(){
            const res=await user.queryAllUser(this.formSearch);
            if(res.data.code=== '000'){
                this.tableData=res.data.data.records;
                this.total=res.data.data.total;
            }
        },
        //根据用户名称模糊查询
        async selectUser(){
            const res=await user.queryAllUser(this.formQueryUser);
            if(res.data.code === '000'){
                this.tableData=res.data.data.records;
                this.total=res.data.data.total;
            }
        },     
        //重置表单,表单必须有ref属性的值，还要有数据绑定的数据源，还要有验证规则,prop都不能少，才可以实现关闭表单清空内容
        resetForm(formQueryUser) {
            this.$refs[formQueryUser].resetFields();
        },           
        //多选框选中状态,将userid转换成一个字符串
        handleSelectionChange(val){
            this.userIdsArray=val;
            const idList = [];
            const tagList = [];
            for (const v of this.userIdsArray) {
                idList.push(v.userId)
                tagList.push(v.personName)
            };
            this.tags = tagList
            this.sendMessageFrom.userIds=idList.join(',');
            console.log(this.sendMessageFrom.userIds);
        },
        handleClose(tag) {
            console.log(tag);
            this.tags.splice(this.tags.indexOf(tag), 1);
        },
    }
}
</script>

<style scoped  >
.info_block{
    width: 100%;
    height: 60px;
    margin-top: 20px;
    box-sizing: border-box;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    border-radius: 5px;
}

.from_block{

    margin-top: 30px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    border-radius: 5px;
}


/* .editor_block{
    margin-top: 30px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
} */
</style>

